/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.Random;

/**
 *
 * @author trietto
 */
public class Common {

    /**
     *	Create list by <ul> and <li> tags
     *	Items is separated by comma
     **/
    public static String createList(String id, String name, String[] arrItems, String selected) {
        StringBuilder builder = new StringBuilder();
        builder.append("<ul id='" + id + "' name='" + name + "'>");
        for (String item : arrItems) {
            item = item.trim();
            if (item.equalsIgnoreCase(selected)) {
                builder.append("<li><b>" + item + "</b></li>");
            } else {
                builder.append("<li>" + item + "</li>");
            }
        }
        builder.append("</ul>");
        return builder.toString();
    }

    public static String createButton(String id, String name, String value, String attributes) {
        String strName = WebConst.EMPTY.equals(name) ? WebConst.EMPTY : " name = \"" + name + "\"";
        String strId = WebConst.EMPTY.equals(id) ? WebConst.EMPTY : " id = \"" + id + "\"";
        String strAttr = WebConst.EMPTY.equals(attributes) ? WebConst.EMPTY : " " + attributes;
        String strValue = WebConst.EMPTY.equals(value) ? WebConst.EMPTY : " value=\"" + value + "\"";
        return "<input type=\"button\"" + strName + strId + strAttr + strValue + " class=\"button\" />";
    }

    public static String createSubmitButton(String id, String name, String value, String attributes) {
        String strName = WebConst.EMPTY.equals(name) ? WebConst.EMPTY : " name = \"" + name + "\"";
        String strId = WebConst.EMPTY.equals(id) ? WebConst.EMPTY : " id = \"" + id + "\"";
        String strAttr = WebConst.EMPTY.equals(attributes) ? WebConst.EMPTY : " " + attributes;
        String strValue = WebConst.EMPTY.equals(value) ? WebConst.EMPTY : " value=\"" + value + "\"";
        return "<input type=\"submit\"" + strName + strId + strAttr + strValue + " class=\"button\" />";
    }

    /**
     * create textbox control
     * @param id text box id
     * @param name text box name
     * @param value value
     * @param attributes attributes
     * @param className class name
     * @return
     */
    public static String createTextbox(String id, String name, String value, String attributes, String className) {
        String strName = WebConst.EMPTY.equals(name) ? WebConst.EMPTY : " name = \"" + name + "\"";
        String strId = WebConst.EMPTY.equals(id) ? WebConst.EMPTY : " id = \"" + id + "\"";
        String strAttr = WebConst.EMPTY.equals(attributes) ? WebConst.EMPTY : " " + attributes;
        String strValue = WebConst.EMPTY.equals(value) ? WebConst.EMPTY : " value=\"" + value + "\"";
        String strClassName = WebConst.EMPTY.equals(className) ? WebConst.EMPTY : " class=\"" + className + "\"";
        return "<input type=\"text\"" + strName + strId + strAttr + strValue + strClassName + " />";
    }

    /**
     * create password control
     * @param id text box id
     * @param name text box name
     * @param value value
     * @param attribues attributes
     * @return
     */
    public static String createPasswordField(String id, String name, String value, String attribues) {
        return "<input type=\"password\" id=\"" + id + "\" name=\"" + name + "\" value=\"" + value + "\" " + attribues + "/>";
    }

    public static String createComboBox(String id, String name, String[] arrItems, String selected, String attribues) {
        String result = "<select id=\"" + id + "\" name=\"" + name + "\" " + attribues + ">";
        for (String item : arrItems) {
            if (item == null) {
                continue;
            }
            item = item.trim();
            if (item.equals("")) {
                continue;
            }
            String optionName = item.indexOf("\t") == -1 ? item : item.split("\t")[0];
            String optionValue = item.indexOf("\t") == -1 ? item : item.split("\t")[1];
            result += "<option value=\"" + optionValue + "\" title= \"" + optionName + "\"" + (optionValue.equalsIgnoreCase(selected) ? "selected=\"selected\"" : "") + ">" + optionName + "</option>";
        }
        result += "</select>";
        return result;
    }

    public static String createComboBox(String id, String name, String list, String selected, String attribues) {
        String[] arrItems = list != null ? list.split(",") : new String[]{};
        String[] options = new String[arrItems.length];
        String startTag = "<select id=\"" + id + "\" name=\"" + name + "\" " + attribues + ">";
        String endTag = "</select>";
        for (int i = 0; i < arrItems.length; i++) {
            String item = arrItems[i].trim();
            if (item.equals("")) {
                continue;
            }
            String optionName = item.indexOf("\t") == -1 ? item : item.split("\t")[0];
            String optionValue = item.indexOf("\t") == -1 ? item : item.split("\t")[1];
            if (selected.isEmpty() && i == 0) {
                options[i] = "<option value=\"" + optionName + "\" title=\"" + optionValue + "\" selected=\"selected\">" + optionName + "</option>";
            } else {
                options[i] = "<option value=\"" + optionName + "\" title=\"" + optionValue + "\"" + (optionValue.equalsIgnoreCase(selected) ? "selected=\"selected\"" : "") + ">" + optionName + "</option>";
            }
        }
        String result = "";
        result += startTag;
        for (String option : options) {
            if (option == null || option.isEmpty()) {
                continue;
            }
            result += option;
        }
        result += endTag;
        return result;
    }

    /**
     * create check box control
     * @param id
     * @param name
     * @param checked
     * @param value
     * @param caption
     * @param attributes
     * @return
     */
    public static String createCheckBox(String id, String name, boolean checked, String value, String caption, String attributes) {
        String strName = WebConst.EMPTY.equals(name) ? WebConst.EMPTY : " name = \"" + name + "\"";
        String strId = WebConst.EMPTY.equals(id) ? WebConst.EMPTY : " id = \"" + id + "\"";
        String strCheck = checked ? " checked=\"checked\"" : WebConst.EMPTY;
        String strAttr = WebConst.EMPTY.equals(attributes) ? WebConst.EMPTY : " " + attributes;
        String strValue = WebConst.EMPTY.equals(value) ? WebConst.EMPTY : " value=\"" + value + "\"";

        String result = WebConst.EMPTY;
        if (WebConst.EMPTY.equals(caption)) {
            result = "<input type=\"checkbox\"" + strName + strId + strCheck + strAttr + strValue + " class=\"box\" />";
        } else {
            result = "<input type=\"checkbox\"" + strName + strId + strCheck + strAttr + strValue + " class=\"box\" /> " + caption;
        }
        return result;
    }

    /**
     * create radio button
     * @param id
     * @param name
     * @param value
     * @param caption
     * @param checked
     * @param disabled
     * @param attribute
     * @return
     */
    public static String createRadioButton(String id, String name, String value, String caption, boolean checked, boolean disabled, String attribute) {
        String result = "<input type=\"radio\" class=\"box\" id=\"" + id + "\" name=\"" + name + "\" value=\"" + value + "\" "
                + (checked ? "checked=\"checked\"" : "") + " "
                + (disabled ? "disabled=\"disabled\"" : "")
                + " " + attribute + "> " + caption;
        return result;
    }

    public static String createOperatorList(String id, String name, String list, String selected, String width, String attrs) {
        String[] arr = list.split(",");
        String result = "<select id=\"" + id + "\" name=\"" + name + "\" style=\"width: " + width + ";\" " + attrs + ">";
        for (String option : arr) {
            result += "<option value=\"" + option + "\" " + (option.equalsIgnoreCase(selected) ? "selected=\"selected\"" : "") + ">" + option + "</option>";
        }
        result += "</select>";
        return result;
    }

    /**
     * create dialog using by Page and Panel
     * @param title
     * @param content
     * @return
     */
    public static String createDialog(String title, StringBuilder content) {
        StringBuilder builder = new StringBuilder();

        builder.append("<div class=\"pbox\">");
        builder.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");

        // header row
        builder.append("<tr>"
                + "<td class=\"ptl\"></td>"
                + "<td class=\"ptc\">"
                + "<div class=\"fr\" id=\"pclose\">"
                + "<a href=\"javascript:void(0)\" title=\"close\" onclick=\"Dashboard.closeWindow();\"></a>"
                + "</div>"
                + "<h2>"
                + title
                + "</h2>"
                + "</td>"
                + "<td class=\"ptr\"></td>"
                + "</tr>");

        // content row
        builder.append("<tr>"
                + "<td class=\"pl\"></td>"
                + "<td class=\"pc\">");
        builder.append(content);
        builder.append("</td>"
                + "<td class=\"pr\"></td>"
                + "</tr>");

        // footer row
        builder.append("<tr>"
                + "<td class=\"pbl\"></td>"
                + "<td class=\"pbc\"></td>"
                + "<td class=\"pbr\"></td>"
                + "</tr>");
        builder.append("</table></div>");

        return builder.toString();
    }

    /**
     * create image button
     * @param title
     * @param text
     * @param imageUrl
     * @param className
     * @param onClickEventHandler
     * @param attributes
     * @return
     */
    public static final String createImageButton(String title, String text, String imageUrl, String className, String onClickEventHandler, String attributes) {
        String strTitle = WebConst.EMPTY.equals(title) ? WebConst.EMPTY : " title=\"" + title + "\" alt=\"" + title + "\"";
        String strEvent = WebConst.EMPTY.equals(onClickEventHandler) ? WebConst.EMPTY : " onclick=\"" + onClickEventHandler + "\"";
        String strText = WebConst.EMPTY.equals(text) ? WebConst.EMPTY : "&nbsp;" + text;
        String strAttr = WebConst.EMPTY.equals(attributes) ? WebConst.EMPTY : " " + attributes;
        String strClass = WebConst.EMPTY.equals(className) ? WebConst.EMPTY : " class=\"" + className + "\"";
        return "<button type=\"button\"" + strTitle + strEvent + strClass + "><img src=\"" + imageUrl + "\"" + strAttr + "/>" + strText + "</button>";
    }

    /**
     * create hidden field
     * @param id
     * @param name
     * @param value
     * @return
     */
    public static final String createHiddenField(String id, String name, String value) {
        String strName = WebConst.EMPTY.equals(name) ? WebConst.EMPTY : " name = \"" + name + "\"";
        String strId = WebConst.EMPTY.equals(id) ? WebConst.EMPTY : " id = \"" + id + "\"";
        String strValue = WebConst.EMPTY.equals(value) ? WebConst.EMPTY : " value=\"" + value + "\"";

        return "<input type=\"hidden\"" + strId + strName + strValue + " />";
    }

    /**
     * Replace <> from html code
     * @param textInput
     * @return
     */
    public static String HTMLDecrypt(String textInput) {
        String lesster = "&lt;";
        String greater = "&gt;";
        String quote = "&quot;";

        textInput = textInput.replace(lesster, "<");
        textInput = textInput.replace(greater, ">");
        textInput = textInput.replace(quote, "\"");

        return textInput;
    }

    /**
     * Replace <> to html code
     * @param textInput
     * @return
     */
    public static String HTMLEncrypt(String textInput) {
        String lesster = "&lt;";
        String greater = "&gt;";
        String quote = "&quot;";

        textInput = textInput.replace("<", lesster);
        textInput = textInput.replace(">", greater);
        textInput = textInput.replace("\"", quote);

        return textInput;
    }

    synchronized public static String uniqueid() {
        // extension of base time, in milliseconds, representing the days between, roughly, 1/1/1970 and 8/1/2008
        long ext = (38 * 365 + 9 + 180 + 31) * 24;		// (the compiler will optimize this to one number)
        ext *= 3600;
        ext *= 1000;

        // the milliseconds since the extended base time
        long current = System.currentTimeMillis();
        long x = current - ext;		// this will make the number smaller, for easier debugging
        int rand;
        if (current == latestTime) {
            // this situation happens when multiple id's are generated, typically
            // during conversion from OG. Use a sequence number to make the value unique
            rand = seqnr++;
            // make sure not to collide with the latest random number
            if (rand == latestRand) {
                rand = seqnr++;
            }
        } else {
            // create a random number (seeded when the WS started)
            rand = random.nextInt(dig2);
            seqnr = 0;
            latestTime = current;
            latestRand = rand;
        }

        // create the guid by concatenating the two "numbers" using a radix that includes
        // digits, lower and upper case letters
        return superRadix(x, alphanums) + superRadix(rand, alphanums);
    }


    	// support unique id's
	public static Random random = new Random(System.currentTimeMillis());
	private static long latestTime = 0;
	private static int latestRand = 0;
	private static int seqnr = 0;
	// range to use for converting long numbers: digits, lower case letters, upper case letters
	// (except l (lower case L), to not confuse with 1 (one))
	private static String alphanums = "0123456789abcdefghijkmnopqrstuvwxyz";

	// two digits
	private static int dig2 = alphanums.length() * alphanums.length();

    	/**
	 * Convert a number to a relatively short representation, using a high radix, using digits and letters,
	 * both lower and upper case (except capitals "I" and "O").
	 * @param number	the number to convert
	 * @return the resulting string
	 */
	static public String superRadix(long num, String charset) {

		if ( num == 0 ) return "0";

		// the actual radix of 60 (the higher the radix, the smaller the resulting representation)
		int radlen = charset.length();

		// generate the digits
		StringBuilder result = new StringBuilder();
		while ( num > 0 ) {
			int mod = (int)(num%radlen);	// get the modulo (remainder) of dividing by 60
			result.insert(0, charset.substring(mod, mod+1));
			num /= radlen;		// integer division
		}
		return result.toString();
	}

}
